"""捕捉异常模块"""

import traceback
from contextlib import ContextDecorator

from loguru import logger


class TryExcept(ContextDecorator):

    def __init__(self, tag='', not_raise=True, level: str = 'error'):
        self.tag = tag
        self.not_raise = not_raise
        self.level = level

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            traces = ''.join(traceback.format_tb(exc_tb))
            message = f'【{self.tag}】\nTraceback:\n{traces}{exc_type.__name__}:{exc_val}'
            match self.level.lower():
                case 'error':
                    logger.error(message)
                case 'warning' | 'warn':
                    logger.warning(message)
                case 'info':
                    logger.info(message)
                case 'debug':
                    logger.debug(message)
                case _:
                    logger.warning(message)

        return self.not_raise
